<?php 
class CloudMaintainService 
{
	protected $m_ServerDO 	= "appcloudcontrol.server.do.ServerSystemDO";	
	protected $m_InstanceDO = "appcloudcontrol.instance.do.InstanceSystemDO";
	protected $m_ControlSvc = "appcloudcontrol.lib.CloudControlService";

	const MAX_INSTNCE_OVERDUE = 864000; //10 days if its changed also need to change store.lib.StoreService;
	
	public function DailyWork()
	{
		$this->UpdateRootRepos();
		$this->UpdateInstanceRepos();
		$this->UpdateUsageStatus();
		$this->SuspendExpiredIntances();
		$this->DestoryOverdueIntances();
	}
	
	public function UpdateRootRepos()
	{
		$cmd = "Repository::Update";
		$controlSvc = BizSystem::getService($this->m_ControlSvc);
		foreach(BizSystem::getObject($this->m_ServerDO)->directfetch() as $server)
		{
			$controlSvc->addCommand($server['Id'],$cmd);
		}
		return ;
	}
	
	public function UpdateInstanceRepos()
	{
		$cmd = "Instance::UpdateRepos";
		$controlSvc = BizSystem::getService($this->m_ControlSvc);
		foreach(BizSystem::getObject($this->m_InstanceDO)->directfetch("[status]='Active'") as $instance)
		{
			$param = array(
				"hostname" 		=> $instance['hostname'],
				"domain"   		=> $instance['domain'],
				"foreign_key"   => $instance['foreign_key'],
			);
			$controlSvc->addCommand($instance['server_id'],$cmd,$param);
		}
		return ;
	}
		
	public function UpdateUsageStatus()
	{
		$cmd = "Instance::StatUsage";
		$controlSvc = BizSystem::getService($this->m_ControlSvc);
		foreach(BizSystem::getObject($this->m_InstanceDO)->directfetch("[status]='Active'") as $instance)
		{
			$param = array(
				"hostname" 		=> $instance['hostname'],
				"domain"   		=> $instance['domain'],
				"foreign_key"   => $instance['foreign_key'],
			);
			$controlSvc->addCommand($instance['server_id'],$cmd,$param);
		}
		return ;		
	}	
	
	public function SuspendExpiredIntances()
	{
		$cmd = "Instance::Suspend";
		$controlSvc = BizSystem::getService($this->m_ControlSvc);
		$timestamp = date("Y-m-d H:i:s" ,time());
		foreach(BizSystem::getObject($this->m_InstanceDO)->directfetch("[status]='Active' AND [end_time]<'$timestamp'") as $instance)
		{
			$param = array(
				"hostname" 		=> $instance['hostname'],
				"domain"   		=> $instance['domain'],
				"foreign_key"   => $instance['foreign_key'],
			);
			$controlSvc->addCommand($instance['server_id'],$cmd,$param);
		}
		return ;
	}	
	
	public function DestoryOverdueIntances()
	{
		$cmd = "Instance::Destory";
		$controlSvc = BizSystem::getService($this->m_ControlSvc);
		$timestamp = date("Y-m-d H:i:s", time() - self::MAX_INSTNCE_OVERDUE );
		foreach(BizSystem::getObject($this->m_InstanceDO)->directfetch("[status]='Suspended' AND [end_time]<'$timestamp'") as $instance)
		{
			$param = array(
				"hostname" 		=> $instance['hostname'],
				"domain"   		=> $instance['domain'],
				"foreign_key"   => $instance['foreign_key'],
			);
			$controlSvc->addCommand($instance['server_id'],$cmd,$param);
		}
		return ;
	}		
}
?>